package com.zonekey.handle;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: 靳俊英
 * @create: 2021-05-25 14:21
 **/
@Component
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        Map<String, Object> map = new HashMap<String, Object>();
        Throwable cause = authException.getCause();

        response.setStatus(HttpStatus.OK.value());
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        try {
            if(cause instanceof InvalidTokenException) {
                JSONObject json = new JSONObject();
                json.put("code", 1);
                json.put("msg", "失败,无效的access_token");
                json.put("error", "invalid_token");
                json.put("error_description", "Invalid access token");
                response.getWriter().write(JSON.toJSONString(json)
                );
            }else{
                JSONObject json = new JSONObject();
                json.put("code", 1);
                json.put("msg", "失败,缺少授权信息access_token");
                json.put("error", "unauthorized");
                json.put("error_description", "missing access token");
                response.getWriter().write(
                        JSON.toJSONString(json)
                );
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
